package views.profile;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Pattern;

import views.others.Refresh;
import views.slidingMenu.HorzScrollWithActivityMenu;
import views.slidingMenu.R;
import webservice.RESTfulClient;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import database.Models.User;
import database.databaseAccessObjects.DAOUser;
/**
 * Handles the user registration activity.
 * 
 */
public class EditProfile extends Activity {
	public static int ACTIVITY_NO = 4;
	private EditText newUsername;
	private EditText newPassword;
	private EditText newConfiPass;
	private EditText newsex;
	private EditText newage;
	private EditText newhome;
	private Button registerButton;
	private Button clearButton;
	private Button backButton;
	
	
	private DAOUser dbHelper;
	
	 @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	        
        //SharedPreferences settings = getSharedPreferences(login.MY_PREFS, 0);
//        Editor editor = settings.edit();
//        editor.putLong("uid", 0);
//        editor.commit();
//        
        dbHelper = new DAOUser(this);
        dbHelper.open();
        setContentView(R.layout.profile);
        initControls();
	    }
	 
	 /**
	  * Handles interface controls.
	 */
	 private void initControls()
	    {
		 Cursor cur = dbHelper.fetchUser(User.getInstance().getUserName(), User.getInstance().getPassword());
		
		for(int i = 0 ; i <= cur.getCount();i++){
			System.out.println(cur.getString(i));
		}
		 String oldName = cur.getString(1);
		 String oldPW = cur.getString(2);
		
		 String oldAge = cur.getString(4);
		 
		 String oldHome = cur.getString(5);
		 String oldsex = cur.getString(6);
		 System.out.println(oldAge+" "+oldHome+" "+oldName+" "+ oldPW);
		 	newUsername = (EditText) findViewById(R.id.nUsername);
		 	newUsername.setHint(oldName);
		 	newPassword = (EditText) findViewById(R.id.nPassword);
		 	newConfiPass = (EditText) findViewById(R.id.nConfiPass);
		 	newage = (EditText) findViewById(R.id.nage);
		 	newage.setHint(oldAge);
		 	newhome= (EditText) findViewById(R.id.nhome);
		 	newhome.setHint(oldHome);
		 	newsex= (EditText) findViewById(R.id.nsex);
		 	newsex.setHint(oldsex);
		 	registerButton = (Button) findViewById(R.id.nUpdate);
		 	clearButton = (Button) findViewById(R.id.nClear);
		 	backButton = (Button) findViewById(R.id.nBack);
	    	
		 	registerButton.setOnClickListener(new Button.OnClickListener() { 
		 		public void onClick (View v){ 
		 			RegisterMe(v); }});
		 	
		 	clearButton.setOnClickListener(new Button.OnClickListener() { 
	    		public void onClick (View v){ 
	    			ClearForm(); }});
	    	
		 	backButton.setOnClickListener(new Button.OnClickListener() { 
	    		public void onClick (View v){ 
	    			BackToLogin(); }});
	    }
	 
	 /**
     * Clears the registration fields.
     */
	 private void ClearForm()
	    {
//	    	saveLoggedInUId(0, "", "");
	    	newUsername.setText("");
	    	newPassword.setText("");
	    	newConfiPass.setText("");
	    	newhome.setText("");
	    	newage.setText("");
	    	newsex.setText("");
	    }
	 
	 /**
	  * Takes user back to login.
	  */
	  private void BackToLogin()
	    {
	    	finish();
	    }
	 
	  /**
	   * Handles the registration process.
	   * @param v
	   */
	 private void RegisterMe(View v)
	    {
		 	//Get user details. 
	    	String username = newUsername.getText().toString();
	    	String password = newPassword.getText().toString();
	    	String confirmpassword = newConfiPass.getText().toString();
	    	String home = newhome.getText().toString();
	    	String sex = newsex.getText().toString();
	    	String age = newage.getText().toString();
	    	User u = User.getInstance();
	    	//Check if all fields have been completed.
	    	if (username.equals("") || password.equals("")){
	    		Toast.makeText(getApplicationContext(), 
	    				"Please ensure all fields have been completed.",
				          Toast.LENGTH_SHORT).show();
	  		return;
	    	}
	    	
	    	//Check password match. 
	    	if (!password.equals(confirmpassword)) {
	    		Toast.makeText(getApplicationContext(), 
	    				"The password does not match.",
				          	Toast.LENGTH_SHORT).show();
	    					newPassword.setText("");
	    					newConfiPass.setText("");
	    		return;
	    	}
	    	
	    	//Encrypt password with MD5.
	    	//password = md5(password);
	    	
	    	//Check database for existing users.
	    	Cursor user = dbHelper.fetchUser(username, password);
	    	if (user == null) {
	    		Toast.makeText(getApplicationContext(), "Database query error",
				          Toast.LENGTH_SHORT).show();
	    	} 
	    	else {
	    		startManagingCursor(user);
	    		
	    		//Check for duplicate usernames
	    		if (user.getCount() > 0) {
	    			Toast.makeText(getApplicationContext(), "The username is already registered",
	  			          Toast.LENGTH_SHORT).show();
	    			stopManagingCursor(user);
	        		user.close();
	    			return;
	    		}
	    		stopManagingCursor(user);
	    		user.close();
	    		user = dbHelper.fetchUser(username, password);
	        	if (user == null) {
	        		Toast.makeText(getApplicationContext(), "Database query error",
	  			          Toast.LENGTH_SHORT).show();
	        		return;
	        	} else {
	        		startManagingCursor(user);
	        		
	        		if (user.getCount() > 0) {
	        			Toast.makeText(getApplicationContext(), "The username is already registered",
	        			          Toast.LENGTH_SHORT).show();
	        			stopManagingCursor(user);
	            		user.close();
	        			return;
	        		}
	        		stopManagingCursor(user);
	        		user.close();
	        	}
	        	Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
	    		Account[] accounts = AccountManager.get(this.getApplicationContext()).getAccountsByType("com.google");
	    		for (Account account : accounts) {
	    		    if (emailPattern.matcher(account.name).matches()) {
	    		        String possibleEmail = account.name;
	    		        if(possibleEmail!=null){
	    		        	u.setPrimaryMail(possibleEmail);
	    		        }
	    		    }
	    		    /**
	    		     * wenn account gefunden und auf server registriert nur login screen sonst register screen anzeigen
	    		     */
	    		}
	    		//Create the new username.
	        	u.setUserName(username);
	        	u.setPassword(password);
	        	u.setAge(age);
	        	u.setHome(home);
	        	u.setSex(sex);
	        	String resp = "";
	        	try {
					resp = new RESTfulClient().serverCreateUser();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(resp.equalsIgnoreCase("{\"retinfo\":\"success\"}"));
				if(resp!="" && resp.equalsIgnoreCase("{\"retinfo\":\"success\"}")){
	    		long id = dbHelper.createUser(u);
	    		if (id > 0) {
	    			Toast.makeText(getApplicationContext(), "Your username was created",
	    			          Toast.LENGTH_SHORT).show();
//	    			saveLoggedInUId(id, username, newPassword.getText().toString());
	    			Intent i = new Intent(v.getContext(), Refresh.class);
		    		startActivity(i);
		    		dbHelper.close();
//		    		SharedPreferences settings = getSharedPreferences(login.MY_PREFS, 0);
//		    		Editor editor = settings.edit();
//		    		editor.putBoolean("dev_reg",true);
//		    		editor.commit();
		    		finish();
	    		}
				}
				else {
	    			Toast.makeText(getApplicationContext(), "Failed to create new username",
	    			          Toast.LENGTH_SHORT).show();
	    		}
	    	}
	    }
	 
//	 private void saveLoggedInUId(long id, String username, String password) {
//			SharedPreferences settings = getSharedPreferences(login.MY_PREFS, 0);
//			Editor editor = settings.edit();
//			editor.putLong("uid", id);
//			editor.putString("username", username);
//			editor.putString("password", password);
//			editor.commit();
//	}
	/**
	 * Hashes the password with MD5.  
	 * @param s
	 * @return
	 */
	private String md5(String s) {
	    try {
	     
	        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();

	        
	        StringBuffer hexString = new StringBuffer();
	        for (int i=0; i<messageDigest.length; i++)
	            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
	        return hexString.toString();

	    } catch (NoSuchAlgorithmException e) {
	        return s;
	    }
	}
}
